package com.chu.interceptor;

import com.chu.entity.Employee;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ResourceBundle;

public class LoginInterceptor implements HandlerInterceptor {


    @Override//开始拦截
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断是否是匿名地址/公开地址/用户未登录情况下就能访问的资源
        //读取匿名地址
        ResourceBundle resourceBundle =  ResourceBundle.getBundle("openAddress");
        String requestURI = request.getRequestURI();
        if(resourceBundle.containsKey(requestURI)){//如果是匿名地址
            return true;
        }
        //判断session是否有值
        Employee employee = (Employee) request.getSession().getAttribute("employee");
        if(employee!=null){
            return true;
        }else{
            //跳转页面
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write("<script>alert('请登录');location.href='/login.jsp'</script>");
            return false;
        }





    }

    @Override//结束拦截
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override//无论是否异常都要执行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
